﻿@page "/counter"
@using BlazorApp1.Data
@using Microsoft.EntityFrameworkCore
@attribute [StreamRendering]

@inject ApplicationDbContext Context;

<PageTitle>租借记录</PageTitle>

<AuthorizeView>
    <Authorized>
        <h1>租借记录</h1>
        
        <table class="table">
            <thead>
            <tr>
                <th>设备名称</th>
                <th>租借人</th>
                <th>租借时间</th>
                <th>退还时间</th>
                <th>备注</th>
            </tr>
            </thead>
            <tbody>
            @foreach (var loan in _loans)
            {
                <tr>
                    <td>@loan.DeviceName</td>
                    <td>@GetLeaseholderName(loan.Leaseholder)</td>
                    <td>@loan.LoanTime</td>
                    <td>@loan.ReturnTime</td>
                    <td>@(string.IsNullOrWhiteSpace(loan.Remark) ? "" : loan.Remark)</td>
                </tr>
            }
            </tbody>
        </table>
    </Authorized>
    <NotAuthorized>
        欢迎，请登录！
    </NotAuthorized>
</AuthorizeView>


@code {
    private List<dynamic> _loans = new();
    private List<UserInfo> _users = new();

    protected override async Task OnInitializedAsync()
    {
        await Context.LoanInfo
            .Join(Context.DeviceInfo, loan => loan.DeviceId, dev => dev.Id, (loan, dev) => new
                {
                    Id = loan.Id,
                    DeviceName = dev.Name,
                    Leaseholder = loan.Leaseholder,
                    LoanTime = loan.LoanTime,
                    ReturnTime = loan.ReturnTime,
                    Remark = loan.Remark
                }
            ).ForEachAsync(o => _loans.Add(o));

        _users = await Context.UserInfo.ToListAsync();
    }

    private string GetLeaseholderName(string id)
    {
        var u = _users.FirstOrDefault(o => o.Id == id);
        if (u != null)
        {
            return u.Name;
        }

        return "";
    }
}